package org.ruoyi.graph2.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ruoyi.domain.vo.ChatModelVo;
import org.ruoyi.graph.constants.GraphConstants;
import org.ruoyi.graph.dto.GraphExtractionResult;
import org.ruoyi.graph.prompt.GraphExtractPrompt;
import org.ruoyi.graph.service.impl.GraphExtractionServiceImpl;
import org.ruoyi.graph.service.llm.impl.DeepSeekGraphLLMServiceImpl;
import org.ruoyi.service.IChatModelService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;


@Slf4j
@Service
@RequiredArgsConstructor
public class WordService {
	private final IChatModelService chatModelService;

	private final DeepSeekGraphLLMServiceImpl deepSeekGraphLLMService;

	private final GraphExtractionServiceImpl graphExtractionService;
	public GraphExtractionResult extractFromTextWithModel(String text, String modelName) {
		log.info("开始从文本中抽取实体和关系，使用模型: {}, 文本长度: {}", modelName, text.length());

		try {
			// 1. 获取模型配置
			ChatModelVo chatModel = chatModelService.selectModelByName(modelName);
			if (chatModel == null) {
				log.warn("未找到模型: {}, 使用默认模型", modelName);
				return graphExtractionService.extractFromText(text);
			}

			// 2. 构建提示词
			String prompt = GraphExtractPrompt.buildExtractionPrompt(text, GraphConstants.DEFAULT_ENTITY_TYPES);

			// 3. 调用LLM（使用指定模型）
			String llmResponse = deepSeekGraphLLMService.extractGraph(prompt, chatModel);

			// 4. 解析响应
			GraphExtractionResult result = graphExtractionService.parseGraphResponse(llmResponse);
			result.setRawResponse(llmResponse);
			result.setSuccess(true);

			log.info("抽取完成，实体数: {}, 关系数: {}, 使用模型: {}",
				result.getEntities().size(), result.getRelations().size(), modelName);

			// ⭐ 调试：如果没有关系，记录原始响应（便于诊断）
			if (result.getRelations().isEmpty() && !result.getEntities().isEmpty()) {
				log.warn("⚠️ LLM 提取到 {} 个实体，但没有提取到任何关系！", result.getEntities().size());
				log.warn("LLM 原始响应预览（前500字符）: {}",
					llmResponse.length() > 500 ? llmResponse.substring(0, 500) + "..." : llmResponse);
			}

			return result;

		} catch (Exception e) {
			log.error("实体关系抽取失败，模型: {}", modelName, e);
			return GraphExtractionResult.builder()
				.entities(new ArrayList<>())
				.relations(new ArrayList<>())
				.success(false)
				.errorMessage(e.getMessage())
				.build();
		}
	}


}
